package com.tico.editor.editors.controller.websocket;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/webSocket/{random_num}")
@Component
public class HttpWebSocket {
        private static int onlineCount = 0;
        private static Map<String, HttpWebSocket> clients = new ConcurrentHashMap<String, HttpWebSocket>();
        private static Map<String, Session> sessionMap = new ConcurrentHashMap<String, Session>();
        private Session session;
        private String random_num;

        @OnOpen
        public void onOpen(@PathParam("random_num") String random_num, Session session) throws IOException {
            this.random_num = random_num;
            this.session = session;
            addOnlineCount();
            sessionMap.put(random_num,session);
            clients.put(random_num, this);
            System.out.println("已连接");
        }

        @OnClose
        public void onClose() throws IOException {
            subOnlineCount();
        }

        @OnMessage
        public void onMessage(String message) throws IOException {
        }

        @OnError
        public void onError(Session session, Throwable error) {
            error.printStackTrace();
        }

        //根据key发送
        public static void sendMessage(String keys,String message) throws IOException {
            for(String key:sessionMap.keySet()){
                if(keys.equals(key)){
                    sessionMap.get(key).getAsyncRemote().sendText(message);
                }
            }
        }

        public static synchronized int getOnlineCount() {
            return onlineCount;
        }

        public static synchronized void addOnlineCount() {
            HttpWebSocket.onlineCount++;
        }

        public static synchronized void subOnlineCount() {
            HttpWebSocket.onlineCount--;
        }

        public static synchronized Map<String, HttpWebSocket> getClients() {
            return clients;
        }
    }
